const path = require('path');
const webpack = require('webpack');
const ThemeColorReplacer = require('webpack-theme-color-replacer');
const { getThemeColors, modifyVars } = require('./src/utils/themeUtil');
const { resolveCss } = require('./src/utils/theme-color-replacer-extend');
const CompressionWebpackPlugin = require('compression-webpack-plugin');
const { basename } = require('path');
const productionGzipExtensions = ['js', 'css'];
const isProd = process.env.NODE_ENV === 'production';
const assetsCDN = {
  // webpack build externals
  externals: {
    // vue: 'Vue',
    // 'vue-router': 'VueRouter',
    // vuex: 'Vuex',
    // axios: 'axios',
    // nprogress: 'NProgress',
    // clipboard: 'ClipboardJS',
    // '@antv/data-set': 'DataSet',
    // 'js-cookie': 'Cookies'
  },
  css: [
  ]
  // js: [
  //   '//cdn.jsdelivr.net/npm/vue@2.6.11/dist/vue.min.js',
  //   '//cdn.jsdelivr.net/npm/vue-router@3.3.4/dist/vue-router.min.js',
  //   '//cdn.jsdelivr.net/npm/vuex@3.4.0/dist/vuex.min.js',
  //   '//cdn.jsdelivr.net/npm/axios@0.19.2/dist/axios.min.js',
  //   '//cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.js',
  //   '//cdn.jsdelivr.net/npm/clipboard@2.0.6/dist/clipboard.min.js',
  //   '//cdn.jsdelivr.net/npm/@antv/data-set@0.11.4/build/data-set.min.js',
  //   '//cdn.jsdelivr.net/npm/js-cookie@2.2.1/src/js.cookie.min.js'
  // ]
};

module.exports = {
  // lintOnSave: false,
  devServer: {
    proxy: {
      '/api': {
        target: process.env.VUE_APP_API_TARGET_URL,
        // target: 'http://10.70.19.170:8184',
        // headers: { Connection: 'keep-alive' }, // 解决mac Proxy error
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  },
  pluginOptions: {
    'style-resources-loader': {
      preProcessor: 'less',
      patterns: [path.resolve(__dirname, './src/theme/theme.less')]
    }
  },
  configureWebpack: config => {
    config.entry.app = ['babel-polyfill', 'whatwg-fetch', './src/main.js'];
    config.performance = {
      hints: false
    };
    config.plugins.push(
      new ThemeColorReplacer({
        fileName: process.env.VUE_APP_BUILD_SOURCE_PATH + '/css/theme-colors-[contenthash:8].css',
        matchColors: getThemeColors(),
        injectCss: true,
        resolveCss
      })
    );
    // Ignore all locale files of moment.js
    config.plugins.push(new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/));
    // 生产环境下将资源压缩成gzip格式
    if (isProd) {
      // add `CompressionWebpack` plugin to webpack plugins
      config.plugins.push(new CompressionWebpackPlugin({
        algorithm: 'gzip',
        test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
        threshold: 10240,
        minRatio: 0.8
      }));
    }
    // if prod, add externals
    if (isProd) {
      config.externals = assetsCDN.externals;
    }
  },
  chainWebpack: config => {
    // // 分析chunk
    // config.plugin('webpack-bundle-analyzer')
    //   .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin);

    // 生产环境下关闭css压缩的 colormin 项，因为此项优化与主题色替换功能冲突
    if (isProd) {
      config.plugin('optimize-css')
        .tap(args => {
          args[0].cssnanoOptions.preset[1].colormin = false;
          return args;
        });
    }

    // splitChunks
    if (isProd) {
      config.optimization.splitChunks({
        cacheGroups: {
          common: {
            name: 'chunk-common',
            chunks: 'initial',
            minChunks: 2,
            maxInitialRequests: 5,
            minSize: 0,
            priority: 1,
            reuseExistingChunk: true
          },
          vendors: {
            name: 'chunk-vendors',
            test: /[\\/]node_modules[\\/]/,
            chunks: 'initial',
            priority: 2,
            reuseExistingChunk: true,
            enforce: true
          },
          antDesignVue: {
            name: 'chunk-ant-design-vue',
            test: /[\\/]node_modules[\\/]ant-design-vue[\\/]/,
            chunks: 'initial',
            priority: 3,
            reuseExistingChunk: true,
            enforce: true
          },
          antv: {
            name: 'chunk-antv',
            test: /[\\/]node_modules[\\/]@antv[\\/]/,
            chunks: 'initial',
            priority: 4,
            reuseExistingChunk: true,
            enforce: true
          }
        }
      });
    }

    if (isProd) {
      // config.plugin('html')
      //   .tap(args => {
      //     args[0].cdn = assetsCDN;
      //     return args;
      //   });

      config.optimization.minimizer('terser').tap((args) => {
        args[0].terserOptions.compress.drop_console = true;
        args[0].terserOptions.compress.drop_debugger = true;
        args[0].terserOptions.compress.pure_funcs = ['console.log'];
        args[0].terserOptions.output = {
          comments: false
        };
        return args;
      });
    }
    const svgRule = config.module.rule('svg');
    svgRule.uses.clear();
    svgRule
      .use('babel-loader')
      .loader('babel-loader')
      .end()
      .use('vue-svg-loader')
      .loader('vue-svg-loader').options({
        svgo: {
          plugins: [
            {
              prefixIds: {
                prefix: (node, { path }) => basename(path, '.svg'),
                delim: '-'
              }
            }
          ]
        }
      });

    config.module
      .rule('font-ttf')
    // .test(/\.(woff2?|eot|ttf|otf|ttc)(\?.*)?$/)
      .test(/\.(ttc)(\?.*)?$/)
      .use('url-loader')
      .loader('url-loader')
      .options({
        limit: 20000,
        name: 'fonts/[name]-[hash:7].[ext]', // `fonts/[name]-[hash].[ext]`,
        outputPath: 'fonts/',
        esModule: false
      })
      .end();
  },
  css: {
    loaderOptions: {
      less: {
        lessOptions: {
          modifyVars: modifyVars(),
          javascriptEnabled: true
        }
      }
    }
  },
  publicPath: process.env.VUE_APP_PUBLIC_PATH,
  outputDir: 'dist',
  assetsDir: process.env.VUE_APP_BUILD_SOURCE_PATH + '/static',
  productionSourceMap: false
};
